﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using PPAP.BO;
using PPAP.Model;

namespace PPAP.Web.Part
{
    public partial class PPARTab : PageBase
    {
        PPARBO ppbo = new PPARBO();
        PARTBO pabo = new PARTBO();
        LogBO lbo = new LogBO();

        DictionaryBO dbo = new DictionaryBO();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                if (Request.QueryString["RID"] != null)
                {
                    LoadPlant(Request.QueryString["RID"].ToString());
                    LoadItem();
                    LoadDate(Request.QueryString["RID"].ToString());
                }
            }
            if ((Request.QueryString["his"] != null && Request.QueryString["his"].ToString() == "1")||(CurrentUser.UnitId!="0"&&CurrentUser.UnitId!="99"))  //从历史页面查看或QE无法修改提交信息
            {
                txtDeliveredPartsQuantity.Enabled = false;
                txtDeliveryCourierCompany.Enabled = false;
                txtDeliveryNoteNumber.Enabled = false;
                txtECUHW.Enabled = false;
                txtECUSW.Enabled = false;
                txtModificationScope.Enabled = false;
                txtPressPartMarkingNest.Enabled = false;
                txtPressPartPressCycle.Enabled = false;
                txtPressPartRevisionNumber.Enabled = false;
                txtQLevel.Enabled = false;
                txtRemarks.Enabled = false;
                txtSupplierPartName.Enabled = false;
                txtSupplierPartNo.Enabled = false;
                ddlInitialSampling.Enabled = false;
                ddlLevel.Enabled = false;
                ddlMonth.Enabled = false;
                ddlOtherSamples.Enabled = false;
                ddlPlant.Enabled = false;
                ddlYear.Enabled = false;
                rboInitialSampling.Enabled = false;
                rboOtherSamples.Enabled = false;
                Button1.Visible = false;
                cbPPARWithoutSample.Enabled = false;
                dpDeliveryNoteDate1.Enabled = false;
                rboOtherSamples0.Enabled = false;
                ImageButton1.Enabled = false;
                ImageButton2.Enabled = false;
            }
        }

       

        /// <summary>
        /// 加载数据字典
        /// </summary>
        private void LoadItem()
        {
            ddlInitialSampling.Items.Clear();
            ddlOtherSamples.Items.Clear();
            DataSet dsInitial = dbo.GetDictionaryByParentid(2);
            DataSet dsOther = dbo.GetDictionaryByParentid(3);
            foreach (DataRow dr in dsInitial.Tables[0].Rows)
            {
                ddlInitialSampling.Items.Add(new ListItem(dr["name"].ToString(), dr["code"].ToString()));
            }
            foreach (DataRow dr in dsOther.Tables[0].Rows)
            {
                ddlOtherSamples.Items.Add(new ListItem(dr["name"].ToString(), dr["code"].ToString()));
            }
        }

        /// <summary>
        /// 加载工厂
        /// </summary>
        /// <param name="pparid"></param>
        private void LoadPlant(string pparid)
        {
            DataSet ds = ppbo.GetPlantListForPPARid(pparid);
            if (ds.Tables[0].Rows.Count > 0)
            {
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    ddlPlant.Items.Add(new ListItem(dr["plantname"].ToString(),dr["id"].ToString()));
                }
            }
            else
            {
                ddlPlant.Items.Add(new ListItem("Not added plant information", "0"));
            }
        }

        protected override void SkinControl()
        {
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Button1_Click(object sender, EventArgs e)
        {
            PPAR p = ppbo.GetModel(int.Parse(Request.QueryString["RID"].ToString()));
            PART r = pabo.GetModelForPPARid(int.Parse(Request.QueryString["RID"].ToString()));
            if (p != null&&r!=null)
            {
                r.SUPPLIERPARTNAME = txtSupplierPartName.Text;
                r.SUPPLIERPARTNO = txtSupplierPartNo.Text;
                r.PLANTID = int.Parse(ddlPlant.SelectedValue); //工厂
                r.REASONFORSAMPLING = rboInitialSampling.Checked ? rboInitialSampling.Text :rboOtherSamples.Checked?rboOtherSamples.Text: rboOtherSamples0.Text; //采样的原因
                r.INTTIALSAMPLING = ddlInitialSampling.SelectedValue; //初始化采样
                r.OTHERSAMPLES = ddlOtherSamples.SelectedValue; //其他采样
                r.QLEVEL = txtQLevel.Text; //QLevel
                r.ELEVEL = ddlLevel.SelectedValue;
                r.MODIFICATIONSCOPE = txtModificationScope.Text;  //ModificationScope
                r.REMARKS = txtRemarks.Text;  //Remarks
                r.ECUHWVERSIONNO = txtECUHW.Text; //ECUHW
                r.ECUSWVERSIONNO = txtECUSW.Text; //ECUSW
                r.PRESSPARTMOP = ddlYear.SelectedValue + "-" + ddlMonth.SelectedValue;
                r.PRESSPARTCYCLE = txtPressPartPressCycle.Text;//press part / press cycle
                r.PRESSPARTNEST = txtPressPartMarkingNest.Text; //press part / marking nest, left or right
                r.PRESSPARTREVISIONNUMBER = txtPressPartRevisionNumber.Text;//press part / revision number

                p.ISWITHOUTSAMPLE = cbPPARWithoutSample.Checked ? 1 : 0;
                p.DELIVERYPQ = txtDeliveredPartsQuantity.Text; //Delivered parts quantity
                p.DELIVERYCOMPANY = txtDeliveryCourierCompany.Text;//Delivery/courier company
                p.DELIVERYNOTEDATE = DateTime.Parse(dpDeliveryNoteDate1.Text.Trim()==""?"1900-01-01":dpDeliveryNoteDate1.Text);//Delivery note date
                p.DELIVERYNOTENUMBER = txtDeliveryNoteNumber.Text; //Delivery note number

                if (p.PPARDATE == null)
                    p.PPARDATE = DateTime.Now;
                if(p.STATUS==0||p.STATUS==4)
                p.STATUS = 1;  //PPAR created
                p.Submittedby = CurrentUser.Id;

                int num = ppbo.UpdateForSupplier(p);
                num += pabo.Update(r);
                lbo.WriteLog(CurrentUser.Id, "Save PPAR", p.ID.ToString());
                if (num > 0)
                {
                   // AlertMessage("Part information has been saved into PPAR system");
                    Page.RegisterStartupScript("AlertReLoad", "<script>alert('Part information has been saved into PPAR system');top.frames['mainFrame'].location.reload();</script>");
                    //Response.Write("<script>alert('Part information has been saved into PPAR system');top.frames['mainFrame'].location.reload();</script>");
                   // Button1.Enabled = false;
                    //base.SendEmailToUser("28212958@qq.com", "Test", @"<html ><head ><title></title></head><body><form ><div>
    //<table width='800px' style='border-color: #2A48CE; border: 1px; border-style: solid;
    //        border-color: Gray; border-spacing: 0px;'>
    //        <tr style='height: 32px;'>
    //            <td style='font-weight: bold;' bgcolor='#D7D7D7' >
    //                 System messages</td> </tr>
    //        <tr>
    //            <td>PPAR state change</td></tr> </table></div></form></body></html>");
                }
            }
        }

        /// <summary>
        /// 加载数据
        /// </summary>
        /// <param name="id"></param>
        private void LoadDate(string id)
        {
            PPAR p = ppbo.GetModel(int.Parse(id));
            PART r = pabo.GetModelForPPARid(int.Parse(id));
            if (p != null&&r!=null)
            {
                txtSupplierPartNo.Text = r.SUPPLIERPARTNO;
                txtSupplierPartName.Text = r.SUPPLIERPARTNAME;
                ddlPlant.SelectedValue = r.PLANTID.ToString();
                rboOtherSamples.Checked = r.REASONFORSAMPLING == "Other samples" ? true : false;
                rboInitialSampling.Checked = r.REASONFORSAMPLING == "Initial sampling" ? true : false;
                rboOtherSamples0.Checked = r.REASONFORSAMPLING == "Re-submission" ? true : false;
                ddlInitialSampling.SelectedValue = r.INTTIALSAMPLING;
                ddlOtherSamples.SelectedValue = r.OTHERSAMPLES;
                txtQLevel.Text = r.QLEVEL == "" ? "001" : r.QLEVEL;
                ddlLevel.SelectedValue = r.ELEVEL;
                txtModificationScope.Text = r.MODIFICATIONSCOPE;
                txtRemarks.Text = r.REMARKS;
                txtECUHW.Text = r.ECUHWVERSIONNO;
                txtECUSW.Text = r.ECUSWVERSIONNO;
                string[] month = r.PRESSPARTMOP.Split('-');
                if (month.Length > 1)
                {
                    ddlYear.SelectedValue = month[0].ToString();
                    ddlMonth.SelectedValue = month[1].ToString();
                }
                txtPressPartPressCycle.Text = r.PRESSPARTCYCLE;
                txtPressPartMarkingNest.Text = r.PRESSPARTNEST;
                txtPressPartRevisionNumber.Text = r.PRESSPARTREVISIONNUMBER;

                cbPPARWithoutSample.Checked = p.ISWITHOUTSAMPLE.ToString() == "1" ? true : false;
                txtDeliveredPartsQuantity.Text = p.DELIVERYPQ;
                txtDeliveryCourierCompany.Text = p.DELIVERYCOMPANY;
                txtDeliveryNoteNumber.Text = p.DELIVERYNOTENUMBER;
                dpDeliveryNoteDate1.Text = p.DELIVERYNOTEDATE == null ? "" : p.DELIVERYNOTEDATE == DateTime.Parse("1900-01-01")?"":DateTime.Parse(p.DELIVERYNOTEDATE == null ? "1900-01-01" : p.DELIVERYNOTEDATE.ToString()).ToString("yyyy-MM-dd");
                cbPPARWithoutSample_CheckedChanged(null, null);
                rboInitialSampling_CheckedChanged(null, null);
            }
            //if (CurrentUser.UnitId == "99")
            //    ddlPlant.Enabled = true;
        }

        protected void cbPPARWithoutSample_CheckedChanged(object sender, EventArgs e)
        {
            if (cbPPARWithoutSample.Checked)
            {
                tr1.Visible = false;
                tr2.Visible = false;
            }
            else
            {
                tr1.Visible = true;
                tr2.Visible = true;
            }
        }

        protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
        {
            try
            {
                int num = int.Parse(txtQLevel.Text);
                num--;
                if (num < 1)
                    num = 1;
                txtQLevel.Text = GetQLevelNum(num);
            }
            catch (Exception)
            {
                txtQLevel.Text = "001";
            }
        }

        protected void ImageButton2_Click(object sender, ImageClickEventArgs e)
        {
            try
            {
                int num = int.Parse(txtQLevel.Text);
                num++;
                txtQLevel.Text = GetQLevelNum(num);

            }
            catch (Exception)
            {
                txtQLevel.Text = "001";
            }
        }

        private string GetQLevelNum(int num)
        {
            string value="";
            switch (num.ToString().Length)
            {
                case 1:
                    value += "00" + num;
                    break;
                case 2:
                    value += "0" + num;
                    break;
                case 3:
                    value += num.ToString();
                    break;
                default:
                    value += "001";
                    break;
            }
            return value;
        }

        protected void rboInitialSampling_CheckedChanged(object sender, EventArgs e)
        {
            if (rboInitialSampling.Checked)
            {
                ddlInitialSampling.Enabled = true;
                ddlOtherSamples.Enabled = false;
            }
            else if (rboOtherSamples.Checked)
            {
                ddlInitialSampling.Enabled = false;
                ddlOtherSamples.Enabled = true;
            }
            else
            {
                ddlInitialSampling.Enabled = false;
                ddlOtherSamples.Enabled = false;
            }
        }
    }
}